package cn.shengchao.controler.question.mq;

import cn.shengchao.examstar.knowledge.acl.ports.repositories.IKnowledgeQuestionRepository;
import cn.shengchao.examstar.knowledge.infrastructure.dao.po.TKnowledgeQuestion;
import com.alibaba.fastjson.JSON;
import com.shengchao.examstar.rpc.question.event.QuestionEvent;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

@Component
public class QuestionEventListener {

    public static final String QUEUE = "question.events.queue";

    @Autowired
    private IKnowledgeQuestionRepository iKnowledgeQuestionRepository;

    @RabbitListener(queues = QUEUE, ackMode = "MANUAL")
    public void handleQuestionEvent(QuestionEvent event, Channel channel, 
                                   @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws Exception {
        System.out.println("Received event: " + JSON.toJSONString(event));
        
        try {
            TKnowledgeQuestion tKnowledgeQuestion = new TKnowledgeQuestion();
            tKnowledgeQuestion.setQuestionId(event.getQuestionId());
            // 根据事件类型执行相应操作
            switch (event.getAction()) {
                case "add":
                    iKnowledgeQuestionRepository.delete(tKnowledgeQuestion);
                    for (Long knowledgeId : event.getKnowledgeIds()) {
                        tKnowledgeQuestion = new TKnowledgeQuestion();
                        tKnowledgeQuestion.setQuestionId(event.getQuestionId());
                        tKnowledgeQuestion.setKnowledgeId(knowledgeId);
                        tKnowledgeQuestion.setStatus(Long.valueOf(event.getQuestionOnlineStatus()));
                        iKnowledgeQuestionRepository.save(tKnowledgeQuestion);
                    }
                    break;
                case "delete":
                    // 记录删除题目日志
                    iKnowledgeQuestionRepository.delete(tKnowledgeQuestion);
                    break;
                case "updateStatus":
                    // 记录状态修改日志
                    tKnowledgeQuestion.setStatus(Long.valueOf(event.getQuestionOnlineStatus()));
                    iKnowledgeQuestionRepository.update(tKnowledgeQuestion);
                    break;
            }
            
            // 消息处理成功，手动确认
            channel.basicAck(deliveryTag, false);
            System.out.println("Message processed successfully and acknowledged: " + event.getQuestionId());
        } catch (Exception e) {
            // 处理失败，拒绝消息并重新入队
            channel.basicNack(deliveryTag, false, true);
            System.err.println("Error processing message, requeued: " + e.getMessage());
            throw e;
        }
    }
}
